import { ref,watch } from 'vue'
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'
import axios  from 'axios'

// 登录
export const useCounterStore = defineStore('counter', () => {
  const router = useRouter()
  // 断言告诉ts不会是null
const LoginTime = ref<string>(JSON.parse(localStorage.getItem('LoginTime') !)?JSON.parse(localStorage.getItem('LoginTime') !):0)

let tel = ref<number>(0)
let code = ref<number>(0)
const handerCode=()=>{
    const config={
      url:'/api/v2/genVeriCode',
      method:'get',
      params:{
         phoneNumber:tel.value,
      }
    }
    axios(config).then(res=>{
      console.log(res)
      const {data} = res
      code.value = data.data
    }).catch(err=>{
      console.log(err)
    })
}

const submitForm=()=>{
   const config ={
    url:'/api/v2/users/loginByPhoneNumber',
    method:'post',
    data:{
      phoneNumber:tel.value,
      veriCode:code.value
    }
   }
   axios(config).then(res=>{
    console.log(res)
     const date =new Date( res.headers.date)
     console.log( res.headers.date)
     console.log(date)
     const hours  = date.getHours() // 提取小时
     const minutes = date.getMinutes() // 提取分钟
     const seconds  = date.getSeconds() // 提取迷
      LoginTime.value = ` ${hours}, ${minutes},${seconds}`
      console.log(LoginTime.value)
    if(res.status === 200){
       alert('2秒后跳转页面')
     setTimeout(()=>{
      router.push('/home')
     },2000)
    }
    
   }).catch(err=>{
    console.log(err)
   })
}
watch(LoginTime,(newValue,oldValue)=>{
    localStorage.setItem('LoginTime',JSON.stringify(newValue))
})

  return { 
    tel,
    code,
    LoginTime,
    handerCode,
    submitForm,
  }
 
})
